package com.jiusit.common;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.sql.ResultSet;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.webbuilder.utils.Base64Util;
import com.webbuilder.utils.DateUtil;
import com.webbuilder.utils.DbUtil;
import com.webbuilder.utils.JsonUtil;
import com.webbuilder.utils.MD5FileUtil;
import com.webbuilder.utils.SysUtil;
import com.webbuilder.utils.WebUtil;

public class UnipayServlet extends HttpServlet {
	private static final  Logger log  =  LoggerFactory.getLogger(UnipayServlet.class);
	private static final long serialVersionUID = 3421005242460829369L;
	
	public void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException {
		//String test="eyJvcmRlcklkIjoiWkZXMjAxNjAyMDExNTUzNTg0MDUiLCJyZXN1bHRDb2RlIjoiMDAwMDAwMDAwIiwibWVySWQiOiI2MDU5MjAxMDAwMDAwMjIiLCJ0eG5BbXQiOiI0MDAiLCJxdWVyeUlkIjoiMjAxNjAyMDExNTU3MTY4MDIwMjUiLCJyZXN1bHRNc2ciOiLkuqTmmJPmiJDlip8ifQ==";
		log.info("UnipayServlet callback respContent:----->"+request.getParameter("respContent"));
		/*String respContent=request.getParameter("respContent");
		//String respContent=test;
		String res="0000";
		try {
			//respContent=URLDecoder.decode(respContent, "utf-8");
			respContent=Base64Util.decode(respContent);
			log.info("ret respContent: "+respContent);
			JSONObject json=new JSONObject(respContent);
			if(json.getString("resultCode").equals("000000000")){
				//支付成功  txnAmt 支付金额的单位是分
				//orderId 是用户支付记录中的商户订单号tran_no,根据商户订单号查询出各个订单的ID
				//1、根据查询支付记录
				String paySql = "select * from zfb_user_account_pay where tran_no = '"+json.getString("orderId")+"'";
				ResultSet rs = DbUtil.query(request, paySql);
				if(rs.next()){
					//查询用户数据
					String userSql = "select a.*,b.cash_rate,b.cash_money,b.fast_rate,c.all_balance from zfb_users a";
					userSql += " left join zfb_user_lv b on a.user_lv = b.vip_code";
					userSql += " left join zfb_user_account c on a.id = c.user_id where a.id = '"+rs.getString("user_id")+"'";
					
					ResultSet userRs = DbUtil.query(request, userSql);
					if(userRs.next()){
						//修改支付记录状态
						String updatePaySql = "update zfb_user_account_pay set pay_status = '02' where tran_no = '"+json.getString("orderId")+"'";
						DbUtil.update(request,updatePaySql);
						if("01".equals(rs.getString("pay_type"))){
							//购买会员
							//查询会员购买订单
							String userLvSql = "select a.*,c.vip_code from zfb_buy_order a";
							userLvSql += " left join zfb_order_commodity b on a.id = b.buy_order_id";
							userLvSql += " left join zfb_user_lv c on b.commodity_id = c.id where a.id = '"+rs.getString("order_id")+"'";
							ResultSet userLvRs = DbUtil.query(request, userLvSql);
							userLvRs.next();
							
							String updateOrder = "update zfb_buy_order set order_status = '02' where id = '"+rs.getString("order_id")+"'";
							String updateGoods = "update zfb_order_commodity set status = '03' where buy_order_id = '"+rs.getString("order_id")+"'";
							String updateUser = "update zfb_users set user_lv = '"+userLvRs.getString("vip_code")+"' where id = '"+rs.getString("user_id")+"'";
							
							DbUtil.update(request, updateOrder);
							DbUtil.update(request, updateGoods);
							DbUtil.update(request, updateUser);
							
							//修改平台账户
							BigDecimal changeMoney = rs.getBigDecimal("pay_money");
					        String update_account_sql = "update zfb_user_account set all_assets = all_assets+"+changeMoney+",all_balance = all_balance +"+changeMoney+" where user_id = 'system'";
					        DbUtil.update(request, update_account_sql);
					        
						}else if("02".equals(rs.getString("pay_type"))){
							
							//查询订单
							String orderSql = "select * from zfb_order_users where order_id = '"+rs.getString("order_id")+"'";
							ResultSet orderRs = DbUtil.query(request, orderSql);
							orderRs.next();
							
							//支付房租，多笔
							Map<String, Object> send = new HashMap();
							send.put("command", "uniOrderPay");
							Map<String, Object> data = new HashMap();
							data.put("order_user_id", orderRs.getString("id"));
							data.put("pay_way", "在线银联");
							data.put("shangwu_no", json.getString("orderId"));
							data.put("ip_address", "");
							data.put("pay_status", "02");
							data.put("pay_money", rs.getString("pay_money"));
							data.put("pay_service_fee", orderRs.getString("service_money"));
							data.put("service_fee_scale", orderRs.getString("service_rate"));
							send.put("data", data);
							JSONObject paramJson = new JSONObject(send);
							String sendString = paramJson.toString();
							Map<String, Object> argsMap = new HashMap();
							argsMap.put("data", sendString);

							System.out.println(argsMap);
							String ret = HttpClientUtil.POSTMethod("http://120.24.15.190/zfb_admin/api/command", argsMap, null);
							System.out.println(ret);

						}else if("03".equals(rs.getString("pay_type"))){
							//快捷支付
							String updateOrder = "update zfb_fast_order set pay_status = '02' where id = '"+rs.getString("order_id")+"'";
							
							//记录log
					        //用户快捷记录支付
					        String insert_log_sql = "insert into zfb_user_account_log(id,log_time,user_id,money_type,";
					        insert_log_sql += "input_money,balance,money_desc,shangwu_no,order_id) values(";
					        insert_log_sql += "'"+SysUtil.getUUID()+"',now(),'"+rs.getString("user_id")+"','01',";
					        insert_log_sql += "'"+rs.getBigDecimal("pay_money")+"','"+userRs.getBigDecimal("all_balance").add(rs.getBigDecimal("pay_money"))+"','用户快捷支付','"+json.getString("orderId")+"','"+rs.getString("order_id")+"')";
					        DbUtil.update(request, insert_log_sql);
					        
					        //用户快捷支付手续费
					        //查询快速支付订单
					        String fastSql = "select * from zfb_fast_order where id = '"+rs.getString("order_id")+"'";
					        ResultSet fastRs = DbUtil.query(request, fastSql);
					        BigDecimal fast_rate = new BigDecimal(0);
					        BigDecimal fast_fee = new BigDecimal(0);
					        if(fastRs.next()){
					        	fast_rate = fastRs.getBigDecimal("service_rate");
					        	fast_fee = fastRs.getBigDecimal("service_money");
					        }
					        
					        insert_log_sql = "insert into zfb_user_account_log(id,log_time,user_id,money_type,";
					        insert_log_sql += "out_money,out_scale,balance,money_desc,shangwu_no,order_id) values(";
					        insert_log_sql += "'"+SysUtil.getUUID()+"',now(),'"+rs.getString("user_id")+"','05',";
					        insert_log_sql += "'"+fast_fee+"','"+fast_rate+"','"+userRs.getBigDecimal("all_balance").add(rs.getBigDecimal("pay_money")).subtract(fast_fee)+"','用户支付，快捷支付的服务费','"+json.getString("orderId")+"','"+rs.getString("order_id")+"')";
					        DbUtil.update(request, insert_log_sql);*/
							
							/*//生成提现
							//查询用户提现手续费
					        BigDecimal cash_money = rs.getBigDecimal("pay_money").subtract(fast_fee);
							BigDecimal cash_rate = userRs.getBigDecimal("cash_rate");
							BigDecimal cash_fee = cash_money.multiply(cash_rate).divide(new BigDecimal(100),4,BigDecimal.ROUND_DOWN);
							cash_fee = cash_fee.add(userRs.getBigDecimal("cash_money"));
							
							String cashOrderId = SysUtil.getUUID();
							String insert_cash_sql = "insert into zfb_user_account_cash(id,user_id,cash_money,cash_scale,cash_fee,real_money,";
					        insert_cash_sql += "cash_way,cash_status,cash_time,cash_bank_card,cash_bank_name,open_addr,owner,";
					        insert_cash_sql += "create_by,create_name,create_time,remarks) values('"+cashOrderId+"','"+rs.getString("user_id")+"','"+cash_money+"','"+cash_rate+"','"+cash_fee+"','"+cash_money.subtract(cash_fee)+"',";
					        insert_cash_sql += "'03','01',now(),'"+userRs.getString("bank_no")+"','"+userRs.getString("bank_name")+"','"+userRs.getString("open_bank_addr")+"','"+userRs.getString("open_bank_name")+"',";
					        insert_cash_sql += "'system','支付接口',now(),'支付完成自动提现申请')";
					        
					        DbUtil.update(request, insert_cash_sql);							
					        
					        //用户提现记录
					        insert_log_sql = "insert into zfb_user_account_log(id,log_time,user_id,money_type,";
					        insert_log_sql += "out_money,out_fee,out_scale,balance,money_desc,order_id) values(";
					        insert_log_sql += "'"+SysUtil.getUUID()+"',now(),'"+rs.getString("user_id")+"','04',";
					        insert_log_sql += "'"+cash_money+"','"+cash_fee+"','"+cash_rate+"','"+userRs.getBigDecimal("all_balance").add(rs.getBigDecimal("pay_money")).subtract(fast_fee).subtract(cash_money)+"','用户快捷支付默认提现','"+cashOrderId+"')";
					        DbUtil.update(request, insert_log_sql);*/
					        
		/*
					        //记录平台log
					        //查询平台账目
					        ResultSet plat_account_rs = DbUtil.query(request,"select * from zfb_user_account where user_id = 'system'");
					        plat_account_rs.next();
					        
					        insert_log_sql = "insert into zfb_user_account_log(id,log_time,user_id,money_type,";
					        insert_log_sql += "input_money,balance,money_desc,shangwu_no,order_id) values(";
					        insert_log_sql += "'"+SysUtil.getUUID()+"',now(),'system','01',";
					        insert_log_sql += "'"+rs.getBigDecimal("pay_money")+"','"+plat_account_rs.getBigDecimal("all_balance").add(rs.getBigDecimal("pay_money"))+"','用户快捷支付','"+json.getString("orderId")+"','"+rs.getString("order_id")+"')";
					        DbUtil.update(request, insert_log_sql);
					        
					        //计算平台支付的第三方服务费
					        //BigDecimal pay_station_scale = new BigDecimal(Var.get("api.pay_station_scale"));
					        BigDecimal pay_station_scale = new BigDecimal("0.2");
					        BigDecimal pay_cost_fee = rs.getBigDecimal("pay_money").multiply(pay_station_scale).divide(new BigDecimal(100),4,BigDecimal.ROUND_DOWN);
					        insert_log_sql = "insert into zfb_user_account_log(id,log_time,user_id,money_type,";
					        insert_log_sql += "out_money,out_scale,balance,money_desc,shangwu_no,order_id) values(";
					        insert_log_sql += "'"+SysUtil.getUUID()+"',now(),'system','06',";
					        insert_log_sql += "'"+pay_cost_fee+"','"+pay_station_scale+"','"+plat_account_rs.getBigDecimal("all_balance").add(rs.getBigDecimal("pay_money")).subtract(pay_cost_fee)+"','用户快捷支付的第三方支付成本','"+json.getString("orderId")+"','"+rs.getString("order_id")+"')";
					        DbUtil.update(request, insert_log_sql);*/
					        
					        /*insert_log_sql = "insert into zfb_user_account_log(id,log_time,user_id,money_type,";
					        insert_log_sql += "out_money,out_fee,out_scale,balance,money_desc,order_id) values(";
					        insert_log_sql += "'"+SysUtil.getUUID()+"',now(),'system','04',";
					        insert_log_sql += "'"+cash_money+"','"+cash_fee+"','"+cash_rate+"','"+plat_account_rs.getBigDecimal("all_balance").add(rs.getBigDecimal("pay_money")).subtract(pay_cost_fee).subtract(cash_money).add(cash_fee)+"','用户提现','"+cashOrderId+"')";
					        DbUtil.update(request, insert_log_sql);*/
					        
		/*
					        //修改用户账户
					        BigDecimal changeMoney = rs.getBigDecimal("pay_money").subtract(fast_fee);
					        String update_account_sql = "update zfb_user_account set all_assets = all_assets+"+changeMoney+",all_balance = all_balance +"+changeMoney+" where user_id = '"+rs.getString("user_id")+"'";
					        DbUtil.update(request, update_account_sql);
					        //修改平台账户
					        changeMoney = rs.getBigDecimal("pay_money").subtract(pay_cost_fee);
					        update_account_sql = "update zfb_user_account set all_assets = all_assets+"+changeMoney+",all_balance = all_balance +"+changeMoney+" where user_id = 'system'";
					        DbUtil.update(request, update_account_sql);
						}else{
							res = "-2";//订单支付类型异常
							//修改支付记录状态
							String updatePaySql1 = "update zfb_user_account_pay set pay_status = '02' where tran_no = '"+json.getString("orderId")+"'";
							DbUtil.update(request,updatePaySql1);
						}
					}else{
						res = "-4";//会员数据异常
						//修改支付记录状态
						String updatePaySql = "update zfb_user_account_pay set pay_status = '02' where tran_no = '"+json.getString("orderId")+"'";
						DbUtil.update(request,updatePaySql);
					}
					
				}else{
					res = "-1";//未找到该订单
					//修改支付记录状态
					String updatePaySql = "update zfb_user_account_pay set pay_status = '02' where tran_no = '"+json.getString("orderId")+"'";
					DbUtil.update(request,updatePaySql);
				}
			}else{
				//支付失败
				res = "-3";//支付失败
				//修改支付记录状态
				String updatePaySql = "update zfb_user_account_pay set pay_status = '02' where tran_no = '"+json.getString("orderId")+"'";
				DbUtil.update(request,updatePaySql);
			}
			WebUtil.writer(response, res);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
	}
	
	
	public static Map getTn(Double money,String shangwu_no){
		Map res=new HashMap();
		try{
			Map<String, Object> argsMap = new HashMap();
			argsMap.put("backUrl","http://www.zufuwang.com/zfb_admin/unipayback");
			argsMap.put("merId","605920100000022");
			argsMap.put("orderId",shangwu_no);//传商户订单号
			argsMap.put("txnAmt",money.intValue());
			argsMap.put("txnTime",DateUtil.formatDate(new Date(), "yyyyMMddHHmmss"));
			String jsonStr=new JSONObject(argsMap).toString();
			log.info("ret argsMap: "+jsonStr);
			//JSON格式请求参数->BASE64，得到reqContent参数
			String reqContent=Base64Util.encode(jsonStr);
			//md5Hex(步骤2的结果+商户密钥)，得到signature参数
			String signature=MD5FileUtil.MD5(reqContent+"pwAbu6cUE8XUXkwV4smmHYxbGuJV8X2J").toLowerCase();//转小写
			//拼接得到HTTP接口请求参数，注意需要对reqContent做urlEncode处理
			Map<String, Object> params = new HashMap();
			params.put("signature", signature);
			//params.put("reqContent", URLEncoder.encode(reqContent, "utf-8"));
			params.put("reqContent", reqContent);
			log.info("ret params: "+params);
			String ret = HttpClientUtil.POSTMethodWidthHeader("https://mpay.sinoqy.com:2070/qyapi/v3/mer/gettn", params, null, null, true);
			log.info("ret raw: "+ret);
			//对respContent做urlDecode，再做BASE64解码，得到应答结果
			String[] respContent_s=ret.split("&");
			String respContent="";
			for (int i = 0; i < respContent_s.length; i++) {
				if(respContent_s[i].startsWith("respContent=")){
					respContent=respContent_s[i].split("=")[1];
				}
			}
			log.info("ret respContent: "+respContent);
			respContent=URLDecoder.decode(respContent, "utf-8");
			respContent=Base64Util.decode(respContent);
			log.info("ret respContent: "+respContent);
			JSONObject json=new JSONObject(respContent);
			if(json.getString("respCode").equals("00")){
				log.info("ret tn: "+json.getString("tn"));
			}else{
				log.info("ret respMsg: "+json.getString("respMsg"));
			}
			res=JsonUtil.getMap(json.toString());
		}catch(Exception e){
			log.error("getTn error " + e.getMessage());
			res.put("respCode", "99");
			res.put("respMsg", e.getMessage());
			e.printStackTrace();
		}
		return res;
	}
	
	/**
	 * 支付结果查询
	 * @param shangwu_no 商户订单号
	 * @param user_id  支付用户ID
	 * @return
	 */
	public static Map checkPay(String shangwu_no,String user_id){
		Map res=new HashMap();
		try{
			Map<String, Object> argsMap = new HashMap();
			argsMap.put("merId","605920100000022");
			argsMap.put("orderId",shangwu_no);//传商户订单号
			argsMap.put("queryId","");
			argsMap.put("txnTime",DateUtil.formatDate(new Date(), "yyyyMMddHHmmss"));
			String jsonStr=new JSONObject(argsMap).toString();
			log.info("ret argsMap: "+jsonStr);
			//JSON格式请求参数->BASE64，得到reqContent参数
			String reqContent=Base64Util.encode(jsonStr);
			//md5Hex(步骤2的结果+商户密钥)，得到signature参数
			String signature=MD5FileUtil.MD5(reqContent+"pwAbu6cUE8XUXkwV4smmHYxbGuJV8X2J").toLowerCase();//转小写
			//拼接得到HTTP接口请求参数，注意需要对reqContent做urlEncode处理
			Map<String, Object> params = new HashMap();
			params.put("signature", signature);
			//params.put("reqContent", URLEncoder.encode(reqContent, "utf-8"));
			params.put("reqContent", reqContent);
			log.info("ret params: "+params);
			String ret = HttpClientUtil.POSTMethodWidthHeader("https://mpay.sinoqy.com:2070/qyapi/v3/mer/query", params, null, null, true);
			log.info("ret raw: "+ret);
			//对respContent做urlDecode，再做BASE64解码，得到应答结果
			String[] respContent_s=ret.split("&");
			String respContent="";
			for (int i = 0; i < respContent_s.length; i++) {
				if(respContent_s[i].startsWith("respContent=")){
					respContent=respContent_s[i].split("=")[1];
				}
			}
			log.info("ret respContent: "+respContent);
			respContent=URLDecoder.decode(respContent, "utf-8");
			respContent=Base64Util.decode(respContent);
			log.info("ret respContent: "+respContent);
			JSONObject json=new JSONObject(respContent);
			//返回结果ret respContent: {"merId":"605920100000022","queryId":"20160304185612340139","orderId":"ZFW20160304184936886","txnTime":"20160304221138","txnAmt":"100","resultCode":"000000000","resultMsg":"交易成功","respCode":"00","respMsg":"成功"}
			if(json.getString("resultCode").equals("000000000")){
				log.info("ret resultMsg: "+json.getString("resultCode"));
				//支付成功
				
			}else{
				log.info("ret resultMsg: "+json.getString("resultCode"));
				//支付失败
			}
			res=JsonUtil.getMap(json.toString());
		}catch(Exception e){
			log.error("getTn error " + e.getMessage());
			res.put("respCode", "99");
			res.put("respMsg", e.getMessage());
			e.printStackTrace();
		}
		return res;
	}
}
